﻿using System;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;

namespace GbopSdk
{
	/// <summary>
	/// 响应
	/// </summary>
	[Serializable]
	public class GbopResponse
	{
		/// <summary>
		/// 生成的验签字符串
		/// </summary>
		private string SignedStr;

		/// <summary>
		/// Header 头
		/// </summary>
		internal HttpRequestHeaders RequestHeaders;

		/// <summary>
		/// 响应结果数据
		/// </summary>
		public string ResponseResult { get; set; }

		/// <summary>
		/// 请求对象
		/// </summary>
		public GbopRequest RequestItem { get; set; }

		/// <summary>
		/// 请求异常信息
		/// </summary>
		public Exception RequestException { get; set; }

		/// <summary>
		/// 是否成功，true：成功，false：失败
		/// </summary>
		public bool IsSuccess { get; set; } = true;

		/// <summary>
		/// 执行时间（毫秒数）
		/// </summary>
		public long ElapsedMilliseconds { get; internal set; }

		/// <summary>
		/// 执行方式
		/// </summary>
		public string ResponseMethod { get; internal set; }

		/// <summary>
		/// 
		/// </summary>
		/// <param name="signStr"></param>
		/// <param name="requestHeaders"></param>
		/// <param name="result"></param>
		internal GbopResponse(string signStr, HttpRequestHeaders requestHeaders, string result)
		{
			this.SignedStr = signStr;
			this.RequestHeaders = requestHeaders;
			this.ResponseResult = result.StartsWith("{") ? JsonHelper.FormatJsonString(result) : result;
		}

		/// <summary>
		/// 字符串
		/// </summary>
		/// <returns></returns>
		public override string ToString()
		{
			return SignedStr + GbopConsts.LF
				+ GetCurInfo()
				+ RequestHeaders + GbopConsts.LF
				+ ResponseResult;
		}

		/// <summary>
		/// Curl命令信息
		/// </summary>
		/// <returns></returns>
		private string GetCurInfo()
		{
			StringBuilder sb = new StringBuilder();
			try
			{
				sb.Append("CURL ").Append(GbopHelper.GetCurArgInfo(this));
				sb.Append(GbopConsts.LF);
			}
			catch
			{

			}
			return sb.ToString();
		}
	}
}